﻿using SqlSugar;
using WorkLogSystem.Options;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class SqlSugarExtensions
    {
        public static IServiceCollection AddSqlSugar(this IServiceCollection services,
        IConfiguration configuration,
        Action<SqlSugarOptions> setupAction = null)
        {
            var options = new SqlSugarOptions();
            setupAction?.Invoke(options);

            var connectionString = configuration.GetConnectionString(options.ConnectionName);

            services.AddSingleton<ISqlSugarClient>(provider =>
            {
                var config = new ConnectionConfig()
                {
                    ConnectionString = connectionString,
                    DbType = options.DbType,
                    IsAutoCloseConnection = options.IsAutoCloseConnection
                };

                return new SqlSugarScope(config, db =>
                {
                    if (options.EnableLogging)
                    {
                        db.Aop.OnLogExecuting = (sql, pars) =>
                        {
                            var logger = provider.GetService<ILogger<ISqlSugarClient>>();
                            logger?.LogInformation($"SQL: {sql}");
                        };
                    }

                    //options.ConfigureScope?.Invoke(db);
                });
            });

            return services;
        }
    }
}
